package main

import (
	"context"
	"cyrus/rabbit-go/conf"
	"log"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

func main() {
	if err := conf.Init(); err != nil {
		log.Fatal("config init failed:", err)
	}

	conn, err := amqp.Dial(conf.Cfg.Rabbit.Dsn)
	if err != nil {
		log.Fatal("connect to RabbitMQ failed:", err)
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		log.Fatal("open channel failed:", err)
	}
	defer ch.Close()

	q, err := ch.QueueDeclare(
		"hello", // name
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // args
	)
	if err != nil {
		log.Fatal("declare queue failed:", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	body := "Hello, 世界"
	if err := ch.PublishWithContext(ctx,
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(body),
		},
	); err != nil {
		log.Fatal("publish a message failed:", err)
	}

	log.Printf(" [x] Sent %s\n", body)
}
